import { defineStore } from 'pinia';
import { goLogin } from '@/api/user.js';
import {uploadDateStatus, todayCanUpload, todayUploadInfo} from '@/api/upload.js';
import { getWxopenid } from '@/utils/getWxOpenId.js';
import {getUserAmount} from "@/api/user_amount";

export const useUserInfo = defineStore('userInfo', {
	state: () => {
		return {
			userData: {
				alipay_user: '',
				auth: '',
				// custom_name: '',
				id: '',
				phone: '',
				// register_image: [],
				// register_time: '',
				wxid: '',
				wxname: '',
				wxopenid: '',
				avatar_url: '',
			},
			clockInCount: 0,
			todayClockIn : {
				canUpload : false,
				detail : '',
				status : -2,
			},
			amount : 0
		};
	},
	// 配置持久化
	persist: {
		// 调整为兼容多端的API
		storage: {
			setItem(key, value) {
				uni.setStorageSync(key, value);
			},
			getItem(key) {
				return uni.getStorageSync(key);
			},
			remove(key) {
				uni.removeStorage({
					key: key,
				});
			},
		},
	},
	getters: {
		async getUserData() {
			return this.userData;
		},
	},
	actions: {
		async initUser() {
			//if (!this.userData) return;
			let wxopenidResult = await getWxopenid();
			if (wxopenidResult.success) {
				let loginResult = await goLogin({
					wxopenid: wxopenidResult.data.openid,
				});
				if (loginResult.success) {
					this.userData = loginResult.data;
					await this.updateUserData(loginResult.data.wxopenid);
				}
			}
		},
		async updateUserData(wxopenid) {
			//更新打卡计数
			this.clockInCount = 0;
			let result = await uploadDateStatus({wxopenid});
			if (result.success) {
				// 遍历接口返回的数据，累加打卡状态为 1 的记录
				result.data.forEach((item, index) => {
					if (item.status === 1) {
						this.clockInCount += 1;
					}
				});
			}

			//检查用户今天打卡记录
			let checkTodayCanUploadResult = await todayUploadInfo({wxopenid});
			console.log("检查用户今天打卡记录",checkTodayCanUploadResult);
			if(checkTodayCanUploadResult.success) {
				this.todayClockIn.canUpload = checkTodayCanUploadResult.data.canUpload;
				this.todayClockIn.detail = checkTodayCanUploadResult.data.detail;
				this.todayClockIn.status = checkTodayCanUploadResult.data.status;
			}

			let userAmountResult = await getUserAmount({wxopenid})
			console.log("获取用户可兑换金额",userAmountResult);
			if(userAmountResult.success){
				this.amount = userAmountResult.data.amount;
			}
		}
	},
});